<?php
// +----------------------------------------------------------------------
// | Yzncms [ 御宅男工作室 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://yzncms.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 御宅男 <530765310@qq.com>
// +----------------------------------------------------------------------

// +----------------------------------------------------------------------
// | 用户自定义函数库
// +----------------------------------------------------------------------
use EasyWeChat\Factory;
use think\Db;
use think\Image;

function conf($val = "", $vals = "")
{
    return config()[$val][$vals];
}

function responseJson($code = 0, $msg = '', $data = null)
{
    $response = array(
        'code' => $code,
        'data' => $data,
        'msg' => $msg
    );
    exit(json_encode($response));
}

function lmcurl($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FAILONERROR, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_AUTOREFERER, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    $SSL = substr($url, 0, 8) == "https://" ? true : false;
    if ($SSL) {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // 检查证书中是否设置域名
    }
    $content = curl_exec($ch);
    curl_close($ch);
    return $content;
}

function msg($code = 0, $msg = "", $data, $count = 1)
{

    $res['code'] = $code;

    $res['msg'] = $msg;

    $res['data'] = $data;

    $res['count'] = $count;

    exit(arj($res));

}

function arj($data, $isformdata = 1)
{
    if ($data == '' || empty($data)) return '';

    // if($isformdata) $data = new_stripslashes($data);

    if (version_compare(PHP_VERSION, '5.3.0', '<')) {
        return json_encode($data, JSON_UNESCAPED_UNICODE);
    } else {
        return json_encode($data, JSON_UNESCAPED_UNICODE);
    }
}

/**
 * 获取微信小程序token
 * @return bool|string
 */
function getAccessToken()
{
    $appid = config('wechat.appID');
    $secret = config('wechat.AppSecret');
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);

    curl_setopt($ch, CURLOPT_HEADER, 0);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    $res = curl_exec($ch);
    curl_close($ch);
    return $res;
}

//获取两点之间的距离 返回为米
function distanceHaversine($lat1, $lon1, $lat2, $lon2)
{
    $earthRadius = 6371; // 地球半径，单位为千米
    $dLat = deg2rad($lat2 - $lat1);
    $dLon = deg2rad($lon2 - $lon1);
    $a = sin($dLat / 2) * sin($dLat / 2) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * sin($dLon / 2) * sin($dLon / 2);
    $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
    $distance = $earthRadius * $c;
    return $distance;
}


function getDistance($from, $to)
{
//
    $lastPos = strrpos($to, ';');
    if ($lastPos !== false) {
        $to = explode(';', $to)[1];
    }
//
    $to = explode(',', $to);

    $from = explode(',', $from);

    $radLat1 = deg2rad(floatval($to[1]));// deg2rad()函数将角度转换为弧度

    $radLat2 = deg2rad(floatval($from[1]));

    $radLng1 = deg2rad(floatval($to[0]));

    $radLng2 = deg2rad(floatval($from[0]));

    $a = $radLat1 - $radLat2;

    $b = $radLng1 - $radLng2;

    $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137;

    return round($s, 2);
}

//通过IP获取地址
function getDistrictByIP($ip)
{
    $url = "http://ip-api.com/json/" . $ip;
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);

    $data = json_decode($response, true);
    if ($data && $data['status'] === 'success') {
        return $data['city']; // 返回区县名
    } else {
        return 'Unknown';
    }
}

//获取订单号
function GetOrderSN($type, $data = array())
{

    if ($type == 1) {


        $city_code = cityCode($data);

        $time = date('ymd');

        $lennum = lennum();

        $ordersn = $time . $city_code . $lennum;

        return $ordersn;
    }

    if ($type == 2) {
        $order_id_main = date('YmdHis') . rand(100000, 999999);
        $order_id_len = strlen($order_id_main);
        $order_id_sum = 0;
        for ($i = 0; $i < $order_id_len; $i++) {
            $order_id_sum += (int)(substr($order_id_main, $i, 1));
        }
        $osn = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT);
        return $osn;
    }

}

/**
 * 区号
 */

function cityCode($data)
{
    $los = $data['lat'] . ',' . $data['lng'];

    $url = "https://apis.map.qq.com/ws/geocoder/v1/?location=" . $los . "&key=" . config('MapKey') . "&type=json";

    $res = lmcurl($url);

    $city = string2array($res);


    if ($city['status'] != 0) {

        GetOrderSN(1, $data);

    }
    $ad_info = $city['result']['ad_info'];

    $length = strlen($ad_info['phone_area_code']);

    $city_code = $ad_info['phone_area_code'];

    if ($length > 3) {
        $city_code = substr($city_code, 1, 3);
    }

    return $city_code;
}

/**
 * 根据地址返回坐标(高德)
 */
function getTencentLngLat($address)
{
    $key = config('wechat.geocodeMap_1');
    $url = 'https://restapi.amap.com/v3/geocode/geo?key=' . $key . '&address=' . urlencode($address);
    $response = file_get_contents($url);
    $jsonResponse = json_decode($response, true);
    if ($jsonResponse['status'] == '1') {
        $jsonResponse['geocodes'][0]['location'] = explode(',', $jsonResponse['geocodes'][0]['location']);
        return json_encode(array(
            'code' => 0,
            'data' => $jsonResponse['geocodes'][0]['location']
        ));
    } else {
        return json_encode(array(
            'code' => -1,
            'data' => $jsonResponse
        ));
    }
}

/**
 *腾讯地图
 */
function getLWByAddress($address)
{
    $key = config('wechat.geocodeMap_ten');
    $url = 'https://apis.map.qq.com/ws/geocoder/v1?address=' . urlencode($address) . '&key=' . $key;
    $response = file_get_contents($url);
    $jsonResponse = json_decode($response, true);
    if ($jsonResponse['status'] == 0) {
        $address = $jsonResponse['result']['location'];
        $data[] = $address['lng'];
        $data[] = $address['lat'];
        return json_encode(array(
            'code' => 0,
            'data' => $data
        ));
    } else {
        return json_encode(array(
            'code' => -1,
            'data' => $jsonResponse
        ));
    }
}

/**
 *腾讯地图 通过坐标地址 获取关键字地址
 */
function getAddressListByKeywords($city, $latitude, $longitude, $keyword, $page)
{
    //https://apis.map.qq.com/ws/place/v1/search
    //https://apis.map.qq.com/ws/place/v1/search
    //https://apis.map.qq.com/ws/place/v1/explore
    $key = config('wechat.geocodeMap_ten');
    $nearby = $latitude . ',' . $longitude . ',10,1';
    $nearby2 = $city . ',0,' . $latitude . ',' . $longitude;
    $url = 'https://apis.map.qq.com/ws/place/v1/search?boundary=region(' . $nearby2 . ')&keyword=' . $keyword . '&page_size=20&page_index=' . $page . '&orderby=_distance&key=' . $key;
    $response = file_get_contents($url);
    $jsonResponse = json_decode($response, true);
    if ($jsonResponse['status'] == 0) {
        return json_encode(array(
            'code' => 0,
            'data' => $jsonResponse['data']
        ));
    } else {
        return json_encode(array(
            'code' => -1,
            'data' => $jsonResponse['message']
        ));
    }
}

/**
 *腾讯地图 通过坐标地址 获取位置信息
 */
function getAddressByLocation($latitude, $longitude)
{
    $key = config('wechat.geocodeMap_ten');
    $nearby = $latitude . ',' . $longitude;
    $url = 'https://apis.map.qq.com/ws/geocoder/v1?location=' . $nearby . '&key=' . $key . '&get_poi=0';
    $response = file_get_contents($url);

    $jsonResponse = json_decode($response, true);

    if ($jsonResponse['status'] == 0) {
        return json_encode(array(
            'code' => 0,
            'data' => $jsonResponse['result']['ad_info']
        ));
    } else {
        return json_encode(array(
            'code' => -1,
            'data' => $jsonResponse['message']
        ));
    }
}

function getAddressByLocation2($latitude, $longitude)
{
    $key = config('wechat.geocodeMap_ten');
    $nearby = $latitude . ',' . $longitude;
    $url = 'https://apis.map.qq.com/ws/geocoder/v1?location=' . $nearby . '&key=' . $key . '&get_poi=0';
    $response = file_get_contents($url);

    $jsonResponse = json_decode($response, true);

    if ($jsonResponse['status'] == 0) {
        return json_encode(array(
            'code' => 0,
            'data' => $jsonResponse['result']
        ));
    } else {
        return json_encode(array(
            'code' => -1,
            'data' => $jsonResponse['message']
        ));
    }
}

//https://apis.map.qq.com/ws/place/v1/search?boundary=nearby(40.040589,116.273543,1000)&keyword=公园&page_size=10&page_index=1&key=IMYBZ-5AKKQ-ERR5D-BIXJS-ELTY3-3ZFFF
//poi  关联
//https://apis.map.qq.com/ws/poi_association/v1?&location=39.99287,116.31025&title=北京大学&key=OB4BZ-D4W3U-*****


/**
 * 获取前天时间戳范围默认昨天
 */
function getTimestamp($day = -1)
{
    $data_string = $day . " day";
    $yesterday = date("Y-m-d", strtotime($data_string));

// 昨天开始时间戳
    $yesterdayStartTimestamp = strtotime($yesterday . " 00:00:00");

// 昨天结束时间戳
    $yesterdayEndTimestamp = strtotime($yesterday . " 23:59:59");

    return array(
        0 => $yesterdayStartTimestamp,
        1 => $yesterdayEndTimestamp
    );
}

/**
 * 获取前天范围内的时间戳
 */
function getTimestampScope($day = -1, $day2 = -1)
{
    $time1 = getTimestamp($day);
    $time2 = getTimestamp($day2);
    return array(
        0 => $time1[0],
        1 => $time2[1]
    );
}

function objectToArray($object)
{
    $jsonString = json_encode($object);
    $array = json_decode($jsonString, true);

    return $array;
}

//生成小程序二维码
function qrcode($name, $value, $page, $width = 600)
{
    try {
        $config = [
            'app_id' => config('wechat.appID'),
            'secret' => config('wechat.AppSecret'),
        ];
        $app = Factory::miniProgram($config);
        $response = $app->app_code->getUnlimit($value, [
            'page' => $page,
            'width' => $width,
        ]);
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $filename = $response->save(ROOT_PATH . 'public/uploads/drivingcode', 'qrcode' . time());
            return config('wechat.url') . '/uploads/drivingcode/' . $filename;
        }
//        msg(-1, '', $response);
        return $response;
    } catch (\Exception $e) {
//        msg(-1, $e->getMessage(), '');
        return $e->getMessage();
    }
}

//通过时间戳范围获取天数
function getDaysFromTimeStamps($startTimestamp, $endTimestamp)
{
    $startDate = new DateTime();
    $startDate->setTimestamp($startTimestamp);

    $endDate = new DateTime();
    $endDate->setTimestamp($endTimestamp);
    $endDate->modify('+1 day'); // 包含结束日期

    $interval = $startDate->diff($endDate);
    return $interval->days;
}

//通过日期范围 获取每天时间戳范围
function getTimestampsInDateRange($startDate, $endDate)
{
    $startTimestamp = strtotime($startDate);
    $endTimestamp = strtotime($endDate);
    $dateRange = array();
    while ($startTimestamp <= $endTimestamp) {
        $dateRange[] = $startTimestamp;
        $startTimestamp = strtotime('+1 day', $startTimestamp);
    }
    return $dateRange;
}

//给两个时间戳 显示所有年月时间戳范围数组
function getAllMonths($startTimestamp, $endTimestamp)
{
    $months = array();
    $currentTimestamp = $startTimestamp;
    while ($currentTimestamp <= $endTimestamp) {
        $months[] = date('Y--m', $currentTimestamp);
        // 获取下个月的第一天的时间戳
        $currentTimestamp = strtotime("+1 month", $currentTimestamp);
    }
    return $months;
}

//通过年月获取时间戳范围
function getMonthTimestampRange($year, $month)
{
    $startTimestamp = strtotime("{$year}-{$month}-01 00:00:00");
    $endTimestamp = strtotime("+1 month", $startTimestamp) - 1;
    return array($startTimestamp, $endTimestamp);
}

//通过年月获这个月每月的时间戳数组 签到使用

function getMonthTimestamps($year, $month)
{
    $daysInMonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);
    $timestamps = [];
    for ($day = 1; $day <= $daysInMonth; $day++) {
        $timestamps[] = strtotime("{$year}-{$month}-{$day}");
    }
    return $timestamps;
}


//检测是否是手机号
function validatePhoneNumber($phoneNumber)
{
    $pattern = '/^\+\d{1,3}\s?\(\d{1,4}\)\s?\d{1,4}-?\d{1,9}$/';
    return preg_match($pattern, $phoneNumber);
}

// 订单核销 订单id ,核销类型 1扫码核销 2核销码核销,核销角色 1商家核销 2员工核销,核销人员id
function verifyGoodsOrder($order_id, $verify_type, $verify_role, $verify_id, $write_code_digits = 0)
{
    Db::startTrans();
    try {
        $order_info = Db::name('order')->find($order_id);
        if (!$order_info) {
            msg(-1, '订单所属不存在', '');
        }

        if ($verify_type == 2 && ($order_info['write_code_digits'] != $write_code_digits)) {
            msg(-1, '数字核销码错误', '');
        }

        if ($order_info['status'] == 4) {
            msg(-1, '订单已取消，无需配送', '');
        }
        if ($order_info['write_status'] == 1) {
            msg(-1, '订单已核销', '');
        }
        //商家核销
        if ($verify_role == 1) {
            if ($order_info['business_id'] != $verify_id) {
                msg(-1, '订单不属于此商家', '');
            }
        } else {
            $employ_info = Db::name('employ')->find($verify_id);
            if ($order_info['business_id'] != $employ_info['business_id']) {
                msg(-1, '订单不属于此商家', '');
            }
        }
        //核销时间
        $now = time();
        if (($now < $order_info['qu_time_start']) || ($now > $order_info['qu_time_end'])) {
            msg(-1, '取货时间未到', '');
        }

        //订单更新
        $update_order = array(
            'id' => $order_id,
            'status' => 3,
            'write_status' => 1,
            'delivery_type' => $verify_type,//核销状态
            'write_time' => time(),
            'write_role' => $verify_role,
            'write_role_id' => $verify_id
        );
        $data_num = Db::name('order')->update($update_order);
        //todo 总营业额 几天到账余额可提现
        //商家金融记录
//        $business_finance_insert = array(
//            'business_id' => $order_info['business_id'],
//            'money' => $order_info['price'],
//            'true_money' => $order_info['price'],
//            'type' => 1,
//            'is_count' => 1,
//            'create_time' => time(),
//            'order_id' => $order_id,
//            'desc' => '订单核销：' . $order_info['order_no']
//        );
//        Db::name('business_finance')->insertGetId($business_finance_insert);

//        Db::name('business')
//            ->where('id', $order_info['business_id'])
//            ->setInc('amount', $order_info['price']);
        //商家销售额增加
        Db::name('business')
            ->where('is_del','=',0)
            ->where('id', $order_info['business_id'])
            ->setInc('business_volume', $order_info['price']);
        //用户拯救食物 用户省钱 增加经验 碳排放量
        Db::name('member')
            ->where('id', $order_info['member_id'])
            ->setInc('order_num');
        $goods_info = Db::name('goods')
            ->find($order_info['goods_id']);
        Db::name('member')
            ->where('id', $order_info['member_id'])
            ->setInc('save_money', $goods_info['old_price'] - $order_info['pay_money']);
        //用户经验 实际支付1元
        $member_info = Db::name('member')->find($order_info['member_id']);
        $experience = config('site.web_per_experience') ? 1 : config('site.web_per_experience');
        $add_experience = $order_info['pay_money'] * $experience;
        if ($add_experience < 1) {
            $add_experience = 1;
        }
        addExperience($order_info['member_id'], $member_info, $add_experience, '订单购买：' . $order_info['order_no']);
        //用户积分 实际支付1元
        $integral = config('site.web_per_integral') ? 1 : config('site.web_per_integral');
        $add_integral = $order_info['pay_money'] * $integral;
        if ($add_integral < 1) {
            $add_integral = 1;
        }
        //
        addFraction($order_info['member_id'], $add_integral, '订单购买：' . $order_info['order_no'], 3);
        //商家碳排放 用户碳排放
        Db::name('member')->where('id', $order_info['member_id'])->setInc('reduction', $order_info['carbon_emissions']);
        Db::name('business') ->where('is_del','=',0)->where('id', $order_info['business_id'])->setInc('reduction', $order_info['carbon_emissions']);
        Db::commit();
        return $data_num;
    } catch (\Exception $e) {
        Db::rollback();
        return -1;
    }

}

//余额到账
function daoZhang($order_info, $desc = '')
{
    $business_finance_insert = array(
        'business_id' => $order_info['business_id'],
        'money' => $order_info['price'],
        'true_money' => $order_info['price'],
        'type' => 1,
        'is_count' => 1,
        'create_time' => time(),
        'order_id' => $order_info['id'],
        'desc' => $desc
    );
    Db::name('business_finance')->insertGetId($business_finance_insert);
    if ($order_info['status']==5){
        Db::name('business') ->where('is_del','=',0)
            ->where('id', $order_info['business_id'])
            ->setInc('business_volume', $order_info['price']);
    }
    Db::name('business') ->where('is_del','=',0)
        ->where('id', $order_info['business_id'])
        ->setInc('amount', $order_info['price']);
    Db::name('order')->update([
        'id' => $order_info['id'],
        'is_to' => 1
    ]);
}

//发送消息 //接收用户id
function sendMessage($member_id, $content, $message_cate_id, $from_role, $from_id)
{
    $insert_data = array(
        'member_id' => $member_id,
        'content' => $content,
        'message_cate_id' => $message_cate_id,
        'from_role' => $from_role,
        'from_id' => $from_id,
        'create_time' => time()
    );
    Db::startTrans();
    try {
        $data_id = Db::name('message')->insertGetId($insert_data);
        Db::commit();
        return $data_id;
    } catch (\Exception $e) {
        Db::rollback();
        return -1;
    }
}

//获取优惠券
function getCoupons($memberId, $coupon_info, $get_type = 1, $invite_member_id = 0)
{
    $now_time = time();
    $insert_data = array(
        'member_id' => $memberId,
        'coupon_id' => $coupon_info['id'],
        'name' => $coupon_info['name'],
        'value' => $coupon_info['value'],
        'min_amount' => $coupon_info['min_amount'],
        'claimed_time' => $now_time,
        'start_time' => $now_time,
        'create_time' => time(),
        'get_type' => $get_type,
        'invite_member_id' => $invite_member_id,
        'desc' => $coupon_info['desc']
    );
    if ($coupon_info['effect_type'] == 1) {
        $insert_data['end_time'] = $coupon_info['effect_end'];
    } else {
        $insert_data['end_time'] = $now_time + ($coupon_info['effect_day'] * 86400);
    }
    //领取张数
    Db::name('coupons')
        ->where('id', '=', $coupon_info['id'])
        ->setInc('claimed_count');
    //增加会员优惠券
    $result_id = Db::name('member_coupons')->insertGetId($insert_data);
    return $result_id;
}

//通过ip返回地址信息
function getCityByIP()
{
    $ip = $_SERVER['REMOTE_ADDR']; // 获取用户的IP地址
    $url = "http://ip-api.com/json/" . $ip . "?lang=zh-CN"; // 构建查询URL

    // 初始化cURL会话
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 将响应作为字符串返回
    curl_setopt($ch, CURLOPT_HEADER, false); // 不需要头部信息

    // 执行cURL请求
    $response = curl_exec($ch);
    curl_close($ch); // 关闭cURL会话

    // 解析JSON响应
    $data = json_decode($response, true);

    // 检查是否成功获取了位置信息
    if ($data['status'] == 'success') {
        return $data; // 返回城市名
    } else {
        return 'Unknown'; // 未知城市
    }
}

//通过城市返回天气情况

function getWeatherByCity($city)
{

    $url = "https://api.lolimi.cn/API/weather/?city=" . $city; // 构建查询URL
    // 初始化cURL会话
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 将响应作为字符串返回
    curl_setopt($ch, CURLOPT_HEADER, false); // 不需要头部信息
    // 执行cURL请求
    $response = curl_exec($ch);
    curl_close($ch); // 关闭cURL会话
    // 解析JSON响应
    $data = json_decode($response, true);
    // 检查是否成功获取了位置信息
//    return $data;
    if ($data['code'] == 1) {
        return $data['data']; // 返回城市名
    } else {
        return 'Unknown'; // 未知城市
    }
}

//退款订单
function tuikuan($order_info, $order_id, $tui_result = '', $is_houtui = 0)
{
    $update_data = array(
        'id' => $order_id,
        'status' => 4,
        'is_tui' => 2,
        'pay_status' => 0,
        'tui_time' => time(),
        'write_code_digits' => null,
        'write_code' => null,
        'tui_reason' => $tui_result,
        'is_houtui' => $is_houtui
    );
    //优惠券
    if ($order_info['mc_id']) {
        Db::name('member_coupons')->update([
            'id' => $order_info['mc_id'],
            'status' => 1,
        ]);
    }
    //订单信息
    Db::name('order')->update($update_data);
}

//判断是不是今天的时间戳
function isToday($timestamp)
{
    $today = date("Y-m-d"); // 今天的日期
    $date = date("Y-m-d", $timestamp); // 给定时间戳的日期
    return $today === $date;
}

//更新商品评分
function updateGoodsEvaluate($goods_id)
{
    //获取商品订单数量
    $where = array(
        'goods_id' => $goods_id,
        'status' => 6,
        'is_tui' => 0
    );
    $order_num = Db::name('order')
        ->where($where)
        ->count();
    //所有订单评价总和
    $order_evaluate_sum = Db::name('order')
        ->where($where)
        ->sum('evaluate');
    $goods_evaluate = sprintf("%.1f", $order_evaluate_sum / $order_num);
    Db::name('goods')->update(
        [
            'id' => $goods_id,
            'evaluate' => $goods_evaluate
        ]
    );
}

//更新商家评分
function updateBusinessEvaluate($business_id)
{
    //获取商家所有有效订单
    //获取商家有效订单所有评分总和
    $where = array(
        'business_id' => $business_id,
        'status' => 6,
        'is_tui' => 0
    );
    $order_num = Db::name('order')
        ->where($where)
        ->count();
    $order_evaluate_sum = Db::name('order')
        ->where($where)
        ->sum('evaluate');
    $goods_evaluate = sprintf("%.1f", $order_evaluate_sum / $order_num);
    Db::name('business')->update(
        [
            'id' => $business_id,
            'evaluate' => $goods_evaluate
        ]
    );
}

//post请求
function request_post($url = '', $param = '')
{
    if (empty($url) || empty($param)) {
        return false;
    }

    $postUrl = $url;
    $curlPost = $param;
    // 初始化curl
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $postUrl);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    // 要求结果为字符串且输出到屏幕上
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    // post提交方式
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
    // 运行curl
    $data = curl_exec($curl);
    curl_close($curl);

    return $data;
}

function GetCenterFromDegrees($data)
{

    if (!is_array($data)) return FALSE;

    $num_coords = count($data);

    $X = 0.0;
    $Y = 0.0;
    $Z = 0.0;

    foreach ($data as $coord) {

        $lat = deg2rad((float)$coord[0]);
        $lon = deg2rad((float)$coord[1]);

        $a = cos($lat) * cos($lon);
        $b = cos($lat) * sin($lon);
        $c = sin($lat);

        $X += $a;
        $Y += $b;
        $Z += $c;
    }

    $X /= $num_coords;
    $Y /= $num_coords;
    $Z /= $num_coords;

    $lon = atan2($Y, $X);
    $hyp = sqrt($X * $X + $Y * $Y);
    $lat = atan2($Z, $hyp);

    return array(rad2deg($lat), rad2deg($lon));
}

function getCenterPosition($coordinates)
{
    $numCoordinates = count($coordinates);
    $center = array('lat' => 0, 'lng' => 0);

    foreach ($coordinates as $coordinate) {
        $center['lat'] += $coordinate['lat'];
        $center['lng'] -= $coordinate['lng'];
    }

    $center['lat'] = $center['lat'] / $numCoordinates;
    $center['lng'] = $center['lng'] / $numCoordinates;

    return $center;
}

//用户等级判定
function setUserLevel($member_id, $member_experience, $experience_count, $member_level)
{
    $experience = $member_experience + $experience_count;
    $level = Db::name('member_level')
        ->where([
            ['is_del', '=', 0],
            ['exp1', '>=', $experience],
            ['exp2', '<=', $experience],
        ])->find();
    if ($level['level'] > $member_level) {
        Db::name('member')->update([
            'id' => $member_id,
            'level' => $level['level']
        ]);
    }
}

//增加用户经验
//增加经验
function addExperience($memberId, $memberInfo, $experience_count = 2, $desc = '用户签到')
{
    //经验流水
    $insert_data = array(
        'member_id' => $memberId,
        'type' => 1,
        'count' => $experience_count,
        'create_time' => time(),
        'desc' => $desc
    );
    Db::name('member_experience')->insertGetId($insert_data);
    Db::name('member')
        ->where('id', '=', $memberId)
        ->setInc('experience', $experience_count);
    setUserLevel($memberId, $memberInfo['experience'], $experience_count, $memberInfo['level']);
}

//增加减少积分
function addFraction($memberId, $fraction_count = 2, $desc = '用户签到', $type = 1, $is_count = 1, $object_cate = '', $object_id = '', $create_id = '')
{
    $insert_data = array(
        'member_id' => $memberId,
        'create_time' => time(),
        'count' => $fraction_count,
        'sign_time' => date('Y-m-d', time()),
        'desc' => $desc,
        'type' => $type,
        'is_count' => $is_count,
        'object_cate' => $object_cate,
        'object_id' => $object_id,
        'create_id' => $create_id,
    );
    Db::name('fraction_record')->insertGetId($insert_data);
    if ($is_count == 1) {
        Db::name('member')
            ->where('id', '=', $memberId)
            ->setInc('fraction', $fraction_count);
    } else {
        Db::name('member')
            ->where('id', '=', $memberId)
            ->setDec('fraction', $fraction_count);
    }
}

//图片编辑圆形
function edit_img($src)
{
    list($w, $h) = getimagesize($src);
    if ($w > $h) {
        $w = $h;
    } else {
        $h = $w;
    }
    $oimgSrc = imagecreatefromstring(file_get_contents($src));
    $oimgDst = imagecreatetruecolor($w, $h);
    imagealphablending($oimgDst, true);
    $transparent = imagecolorallocatealpha($oimgDst, 0, 0, 0, 127);
    imagefill($oimgDst, 0, 0, $transparent);
    $r = $w / 2;
    for ($x = 0; $x < $w; $x++) {
        for ($y = 0; $y < $h; $y++) {
            $c = imagecolorat($oimgSrc, $x, $y);
            $_x = $x - $w / 2;
            $_y = $y - $h / 2;
            if ((($_x * $_x) + ($_y * $_y)) < ($r * $r)) {
                imagesetpixel($oimgDst, $x, $y, $c);
            } else {
                imagesetpixel($oimgDst, $x, $y, $transparent);
            }
        }
    }

    $str = uniqid(mt_rand(), 1);
    $file = '/upload/ai/code/user/wx_tx/' . date('Ymd', time()) . '/';
    $file2 = $_SERVER['DOCUMENT_ROOT'] . $file;
    if (!is_dir($file2))//检测目录是否存在
    {
        mkdir($file2, 0777, true);
    }
    imagesavealpha($oimgDst, true);
    imagepng($oimgDst, $file2 . md5($str) . '.png');
    imagedestroy($oimgDst);
    imagedestroy($oimgSrc);
    return config('wechat.url') . $file . md5($str) . '.png';
}

function addBorder($src)
{
    $image = imagecreatefromstring(file_get_contents($src));
    $borderColor = imagecolorallocate($image, 255, 0, 0);
    $width = imagesx($image);
    $height = imagesy($image);
    // 根据边框宽度和颜色绘制边框
    for ($i = 0; $i < 5; $i++) {
        imagerectangle($image, $i, $i, $width - $i - 1, $height - $i - 1, $borderColor);
    }

// 输出图像
    //header('Content-Type: image/jpeg');
    //imagejpeg($image);
    $str = uniqid(mt_rand(), 1);
    $file = '/upload/ai/code/user/wx_tx/' . date('Ymd', time()) . '/';
    $file2 = $_SERVER['DOCUMENT_ROOT'] . $file;
    if (!is_dir($file2))//检测目录是否存在
    {
        mkdir($file2, 0777, true);
    }
    imagesavealpha($image, true);
    imagepng($image, $file2 . md5($str) . '.png');
    return $file . md5($str) . '.png';

// 释放内存
    imagedestroy($image);
}

function c2($src)
{
    // 载入原始图片
    $sourceImage = imagecreatefromstring(file_get_contents($src));
//    $sourceImage = imagecreatefrompng('source.png');
    $width = imagesx($sourceImage);
    $height = imagesy($sourceImage);

// 边框的颜色和宽度
    $borderColor = imagecolorallocatealpha($sourceImage, 0, 158, 218, 1);
    $borderSize = 20; // 边框的大小

// 给图片添加边框
    for ($x = 0; $x < $width; $x++) {
        for ($y = 0; $y < $height; $y++) {
            // 检查当前像素是否在圆的边界内
            $alpha = (imagecolorat($sourceImage, $x, $y) >> 24) & 0xFF;
            if (((($x - ($width / 2)) * ($x - ($width / 2))) + (($y - ($height / 2)) * ($y - ($height / 2)))) >= (($width / 2) * ($width / 2) - $borderSize * $borderSize) && (($x - ($width / 2)) * ($x - ($width / 2)) + (($y - ($height / 2)) * ($y - ($height / 2)))) <= (($width / 2) * ($width / 2))) {
                // 在边界内则设置边框颜色
                imagesetpixel($sourceImage, $x, $y, $borderColor);
            }
        }
    }

// 输出处理后的图片
//    header('Content-Type: image/png');
//    imagepng($sourceImage);

    $str = uniqid(mt_rand(), 1);
    $file = '/upload/ai/code/user/wx_tx/' . date('Ymd', time()) . '/';
    $file2 = $_SERVER['DOCUMENT_ROOT'] . $file;
    if (!is_dir($file2))//检测目录是否存在
    {
        mkdir($file2, 0777, true);
    }
    imagesavealpha($sourceImage, true);
    imagepng($sourceImage, $file2 . md5($str) . '.png');
// 释放内存
    imagedestroy($sourceImage);
    return config('wechat.url') . $file . md5($str) . '.png';
}

function setSYText($imagePath = '', $text = 'Your Watermark Text', $color = '#ffffff', $fontSize = 20, $fontPath = 'font/fangsong.TTF')
{
// 要处理的图片路径
    //$imagePath = 'uploads/20241210/c3b622d7083e673ebb99e5a01dc2f20b.jpg';
// 实例化图像处理对象
    $image = Image::open($imagePath);
// 添加文字水印
    //$text = 'Your Watermark Text'; // 水印文字
    //$fontPath='font/test.ttf';
    // $fontSize = 20; // 字体大小
    //$color = '#ffffff'; // 水印颜色

// 添加水印，参数依次是水印文字，字体文件，字体大小，颜色以及水印位置
    $image->text($text, $fontPath, $fontSize, $color, 1, 0, -45);
    $image->text($text, $fontPath, $fontSize, $color, 2, 0, -45);
    $image->text($text, $fontPath, $fontSize, $color, 3, 0, -45);
    $image->text($text, $fontPath, $fontSize, $color, 4, 0, -45);
    $image->text($text, $fontPath, $fontSize, $color, 5, 0, -45);
    $image->text($text, $fontPath, $fontSize, $color, 6, 0, -45);
    $image->text($text, $fontPath, $fontSize, $color, 7, 0, -45);
    $image->text($text, $fontPath, $fontSize, $color, 8, 0, -45);
    $image->text($text, $fontPath, $fontSize, $color, 9, 0, -45);
//    for ($i=1;$i<=9;$i++){
//        $image->text($text, $fontPath, $fontSize, $color, $i,0,-45);
//    }
// 保存处理后的图片
    //$savePath = 'uploads/20241210/7ca923f0d4923d6e747c4c07d16015111.jpg';
    //$savePath=$imagePath;

    $img_arr = explode('.', $imagePath);
    $type = $img_arr[count($img_arr)-1];// 图片后缀
    $path = ROOT_PATH . 'public/upload/car_image/';
    if (!is_dir($path)) {
        @mkdir($path);
    }
    $imagePath2='upload/car_image/' . md5(time()).rand(000000,999999) . '.' . $type;

    $image->save($imagePath2);
    return $imagePath2;
}

// 剔除可能出现的图片域名
function replaceImgDomain($img_url = '')
{
    $img_url = !empty($img_url) ? trim($img_url) : '';
    if (empty($img_url)) {
        return '';
    }
    $pattern = "/^(https?:\/\/)?([^\/]+)/";
    $string = preg_replace($pattern, "", $img_url);
    $string = !empty($string) ? trim($string) : '';
    $string = !empty($string) ? ltrim($string, '//') : '';
    //return !empty($string) ? '/' . trim($string, '/') : '';
    return !empty($string) ? trim($string, '/') : '';
}
function getOrderComment($order_id){
    $comment=Db::name('comment')->where(['is_del'=>0,'status'=>1,'order_id'=>$order_id])->find();
    if ($comment){
        $comment['create_time']=date('Y-m-d H:i:s', $comment['create_time']);
        $comment_img=Db::name('comment_img')
            ->where('comment_id','=',$comment['id'])
            ->order('sort')->column('img_url');
        $comment['comment_img']=$comment_img;
    }
    return $comment;
}

function string2array($data) {
//    $data = trim($data);
    if($data == '') return array();
    if(strpos($data, 'array')===0){
        @eval("\$array = $data;");
    }else{
        if(strpos($data, '{\\')===0) $data = stripslashes($data);
        $array=json_decode(htmlspecialchars_decode($data),true);
    }
    return $array;
}









